/* 
    Copyright (c) 2011 Microsoft Corporation.  All rights reserved.
    Use of this sample source code is subject to the terms of the Microsoft license 
    agreement under which you licensed this sample source code and is provided AS-IS.
    If you did not accept the terms of the license agreement, you are not authorized 
    to use this sample source code.  For the terms of the license, please see the 
    license agreement between you and Microsoft.
  
    To see all Code Samples for Windows Phone, visit http://go.microsoft.com/fwlink/?LinkID=219604 
  
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

// Directives
using Microsoft.Devices;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.Media;
using System.Net;
using System.Windows.Documents;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Shell;
using System.Xml.Linq;
using System.Device.Location;
using System.Runtime.Serialization;
using first_learn.GeocodeService;
using Microsoft.Phone.Controls.Maps;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using first_learn;

//using RedCorona.Net;
namespace sdkBasicCameraCS
{
    //class MessageClient
    //{
    //    ClientInfo client;
    //    void Start()
    //    {
    //        Socket sock = Sockets.CreateTCPSocket("www.myserver.com", 2345);
    //        client = new ClientInfo(sock, false); // Don't start receiving yet
    //        client.MessageMode = MessageMode.Length;
    //        client.OnReadMessage += new ConnectionRead(ReadData);
    //        client.BeginReceive();
    //    }

    //    void ReadData(ClientInfo ci, uint code, byte[] bytes, int len)
    //    {
    //        Console.WriteLine("Received " + len + " bytes: " +
    //           System.Text.Encoding.UTF8.GetString(bytes, 0, len));
    //    }
    //}
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        GeoCoordinateWatcher watcher;
        string accuracyText = "";
        string This_address = "";
        double latitude = 0;
        double longitude = 0;
        Socket mySocket = null;
        string add = "sslab14.cs.purdue.edu";
        int port = 2345;
        ManualResetEvent MyEvent = null;

        public MainPage()
        {
            StartLocationService(GeoPositionAccuracy.Default);
            InitializeComponent();

            ApplicationBar = new ApplicationBar();//����һ��ApplicationBar 

            ApplicationBar.IsVisible = true;//����Ӧ�ó������ɼ�
            ApplicationBar.IsMenuEnabled = true;//���ò˵������

            ApplicationBarIconButton button1 = new ApplicationBarIconButton(new Uri("/Icons/dark/appbar.feature.camera.rest.png", UriKind.Relative));//����һ��Button,��������ͼ��·����
            button1.Text = "To Share";//ͼ����ʾ������ΪVideo
            button1.Click += new EventHandler(Share);//ע��Click�¼�

            ApplicationBarIconButton button2 = new ApplicationBarIconButton(new Uri("/Icons/dark/appbar.share.rest.png", UriKind.Relative));
            button2.Text = "MainPage";
            button2.Click += new EventHandler(ToMainPage);

            ApplicationBar.Buttons.Add(button1);//��Button���ӵ�Ӧ�ó������У����������ʹ�ø�Button�ˡ�
            ApplicationBar.Buttons.Add(button2);

            ApplicationBarMenuItem menuItem1 = new ApplicationBarMenuItem("About");//����һ��MenuItem���������ʾ����Ϊ������
            ApplicationBarMenuItem menuItem2 = new ApplicationBarMenuItem("Rate");
            ApplicationBarMenuItem menuItem3 = new ApplicationBarMenuItem("Exit");

            menuItem1.Click += new EventHandler(menuItem1_Click);//ע��MenuItem���Click�¼�
            menuItem2.Click += new EventHandler(menuItem2_Click);
            menuItem3.Click += new EventHandler(menuItem3_Click);


            ApplicationBar.MenuItems.Add(menuItem1);//��MenuItem���ӵ��˵����У����������ʹ�ø�MenuItem�ˡ�
            ApplicationBar.MenuItems.Add(menuItem2);
            ApplicationBar.MenuItems.Add(menuItem3);

            //locateMe();
        }

        public static Guid GetId()
        {
            Guid applicationId = Guid.Empty;

            var productId = XDocument.Load("WMAppManifest.xml").Root.Element("App").Attribute("ProductID");

            if (productId != null && !string.IsNullOrEmpty(productId.Value))
                Guid.TryParse(productId.Value, out applicationId);

            return applicationId;
        }


        #region Application logic


        /// <summary>
        /// Helper method to start up the location data acquisition
        /// </summary>
        /// <param name="accuracy">The accuracy level </param>
        private void StartLocationService(GeoPositionAccuracy accuracy)
        {
            // Reinitialize the GeoCoordinateWatcher
            watcher = new GeoCoordinateWatcher(accuracy);
            watcher.MovementThreshold = 20;

            // Add event handlers for StatusChanged and PositionChanged events
            watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
            watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);

            // Start data acquisition
            watcher.Start();
        }

        /// <summary>
        /// Handler for the StatusChanged event. This invokes MyStatusChanged on the UI thread and
        /// passes the GeoPositionStatusChangedEventArgs
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MyStatusChanged(e));
        }
        /// <summary>
        /// Custom method called from the StatusChanged event handler
        /// </summary>
        /// <param name="e"></param>
        void MyStatusChanged(GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    // The location service is disabled or unsupported.
                    // Alert the user
                    //StatusTextBlock.Text = "location is unsupported on this device";
                    break;
                case GeoPositionStatus.Initializing:
                    // The location service is initializing.
                    // Disable the Start Location button
                    //StatusTextBlock.Text = "initializing location service," + accuracyText;
                    break;
                case GeoPositionStatus.NoData:
                    // The location service is working, but it cannot get location data
                    // Alert the user and enable the Stop Location button
                    //StatusTextBlock.Text = "data unavailable," + accuracyText;
                    break;
                case GeoPositionStatus.Ready:
                    // The location service is working and is receiving location data
                    // Show the current position and enable the Stop Location button
                    //StatusTextBlock.Text = "receiving data, " + accuracyText;
                    break;

            }
        }

        /// <summary>
        /// Handler for the PositionChanged event. This invokes MyStatusChanged on the UI thread and
        /// passes the GeoPositionStatusChangedEventArgs
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => MyPositionChanged(e));
        }

        /// <summary>
        /// Custom method called from the PositionChanged event handler
        /// </summary>
        /// <param name="e"></param>
        void MyPositionChanged(GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            // Update the TextBlocks to show the current location
            //textBox1.Text = e.Position.Location.Latitude.ToString("0.000");
            //textBox2.Text = e.Position.Location.Longitude.ToString("0.000");
            latitude = e.Position.Location.Latitude;
            longitude = e.Position.Location.Longitude;
            map1.SetView(e.Position.Location, 10);
            GeocodeServiceClient client = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");

            client.ReverseGeocodeCompleted += new EventHandler<ReverseGeocodeCompletedEventArgs>(OnReverseGeocodeCompleted);

            ReverseGeocodeRequest request = new ReverseGeocodeRequest();
            request.Credentials = new first_learn.GeocodeService.Credentials();
            request.Credentials.ApplicationId = "AjjGZGtCVs7lEuRn860kGigumg5hhJ8LqKXOIxpk1zwuxxQUgcrFDRWmrYfYCtFg";
            Location loc = new Location();
            loc.Latitude = e.Position.Location.Latitude;
            loc.Longitude = e.Position.Location.Longitude;
            request.Location = loc;
            client.ReverseGeocodeAsync(request);
        }

        private void OnReverseGeocodeCompleted(object sender, ReverseGeocodeCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result.Results.Count >= 0)
                {
                    GeocodeResponse response = e.Result;

                    //textBox3.Text = response.Results[0].DisplayName;
                    This_address = response.Results[0].DisplayName;
                    string[] country = This_address.Split(',');
                    string[] state = country[2].Split(' ');
                    PageTitle.Text = country[1] + ", " + state[1];
                    //System.Collections.ObjectModel.ObservableCollection<GeocodeResult> list = response.Results;
                    //string allName = "";
                    //foreach (GeocodeResult i in list)
                    //{
                    //    allName += i.DisplayName + "  ";
                    //}
                    //textBox3.Text = allName;
                }
                else
                    MessageBox.Show("Sorry, cannot find location!");
            }
        }

        #endregion

        private void locateMe()
        {
            Pushpin p = new Pushpin();
            p.Background = new SolidColorBrush(Colors.Yellow);
            p.Foreground = new SolidColorBrush(Colors.Black);
            p.Location = new GeoCoordinate(latitude, longitude);
            p.Content = "I'm here";
            map1.Children.Add(p);
            map1.SetView(new GeoCoordinate(latitude, longitude), 9);
        }

        void Share(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPageFive.xaml", UriKind.Relative));
        }

        void ToMainPage(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));

        }

        private void menuItem1_Click(object sender, System.EventArgs e)
        {
            // About 
            MessageBox.Show("About this app.");
        }

        private void menuItem2_Click(object sender, System.EventArgs e)
        {
            // Rate 
            MessageBox.Show("Rate this app!");
        }


        private void menuItem3_Click(object sender, System.EventArgs e)
        {
            // exit 
            throw new Exception("exit");
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            //receive the photos of new city
            //receive(string city);
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

    }
}
